﻿
/*============== simpleIRC - http://matthias.van-eeghem.com/ ==============*
 *                                                                         *
 *  File: ServerWindow.cs                                                        *
 *  Project: simpleIRC                                                     *
 *  Author(s): Matthias Van Eeghem <matthias@van-eeghem.com>               *
 *                                                                         *
 * ========================================================================*
 *                                                                         *
 *  This program is free software: you can redistribute it and/or modify   *
 *  it under the terms of the GNU General Public License as published by   *
 *  the Free Software Foundation, either version 3 of the License, or      *
 *  (at your option) any later version.                                    *
 *                                                                         *
 *  This program is distributed in the hope that it will be useful,        *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of         *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *
 *  GNU General Public License for more details.                           *
 *                                                                         *
 *  You should have received a copy of the GNU General Public License      *
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.  *
 *                                                                         *
===========================================================================*/

using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Threading;
using simpleIRC;
using System.Windows.Media;
using System.Windows;

namespace simpleIRC.UI
{
    /// <summary>
    /// This class contains all UI stuff related to servers
    /// </summary>

    public class ServerWindow : QueryList
    {
        /// <summary>
        /// This variable holds a reference to the MainWindow class
        /// </summary>
        MainWindow mainWindow = null;

        /// <summary>
        /// The name of the ServerWindow
        /// </summary>
        private string Name;

        /// <summary>
        /// The Server object this ServerWindow links to
        /// </summary>
        private Server Server;

        /// <summary>
        /// This TreeViewItem holds the TreeViewItem for this ServerWindow object
        /// </summary>
        public TreeViewItem ServerTreeViewItem { get; private set; }

        /// <summary>
        /// This static variable holds a list of all the ServerWindows created
        /// </summary>
        public static List<ServerWindow> List = new List<ServerWindow>();

        /// <summary>
        /// The constructor of the ServerWindow class
        /// </summary>
        /// <param name="name">The server name</param>
        /// <param name="serverIndex">The serverindex</param>
        /// <param name="parentWindow">The reference to the MainWindow object</param>

        public ServerWindow(string name, int serverIndex, MainWindow parentWindow) : base(serverIndex, parentWindow)
        {
            Name = name;
            mainWindow = parentWindow;
            Server = Core.ServerList[serverIndex];
			
            // Add this object to the ServerWindowList
            List.Add(this);
        }

        /// <summary>
        /// This method creates the actual TreeViewItem to the ChannelsTreeView
        /// </summary>

        public void Create()
        {
            ServerTreeViewItem = new TreeViewItem();
            ServerTreeViewItem.Header = Name;
            ServerTreeViewItem.Name = "Server" + Server.Index.ToString();
            mainWindow.CurrentServerWindow = Server.Index;

            TreeViewItem ServerTreeViewItemCopy = ServerTreeViewItem;
            mainWindow.UserInterface.AddRightClickEvent(ref ServerTreeViewItemCopy, "Close", mainWindow.UserInterface.ContextMenu_PartServer);

            // Add the treeview item to the treeviewlist.
            mainWindow.ChannelsTreeView.Items.Add(ServerTreeViewItem);
            ServerTreeViewItem.ExpandSubtree();
            ServerTreeViewItem.IsSelected = true;

            // Create the query list
            CreateQueryList();
        }

        /// <summary>
        /// This function writes the data received to the correct channel on the correct server.
        /// </summary>
        /// <param name="outputLine">The outputline to write</param>
        /// <param name="appendTimestamp">If this bool is set to true, the method prepends a timestamp before the string</param>

        public void SendText(string outputLine, bool appendTimestamp = true)
        {
            if (appendTimestamp) mainWindow.UserInterface.FormatTimestamp(ref outputLine);

            Server.Text += outputLine;

            // We're currently looking at the window it's supposed to go to, just write to it!
            if (mainWindow.CurrentChannelWindow == -1 && mainWindow.CurrentQueryWindow == -1 && mainWindow.CurrentServerWindow == Server.Index)
            {
                // Yep we have to invoke.
                mainWindow.ChatBox.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
                {
                    mainWindow.Colors.HandleColors(outputLine);
                }));
            }
            // We're looking at another server window than the one we're supposed to write to.
            else
            {
                if (Server.Index != mainWindow.CurrentServerWindow && mainWindow.CurrentQueryWindow == -1 && mainWindow.CurrentChannelWindow == -1)
                {
                    mainWindow.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(delegate()
                    {
                        ServerTreeViewItem.Foreground = Brushes.Red;
                    }));
                }
            }
        }

        /// <summary>
        /// This function disconnects the client from the server.
        /// </summary>
        /// <param name="reason">The reason to quit with</param>
        /// <param name="canReconnect">If canReconnect is set to true, the channels aren't destroyed etc.</param>

        public void Disconnect(string reason, bool canReconnect = false)
        {
            string Output = "* Disconnected.\r";

            // Send a message to the server output and all the channels informing the user he disconnected.
            this.SendText(Output);

            // Loop through all channels
            for (int i = 0; i < Core.ChannelList.Count; i++)
            {
                Channel Channel = Core.ChannelList[i];

                if (Channel != null)
                {
                    if (Channel.Server.Index == Server.Index)
                    {
                        ChannelWindow.List[Channel.Index].SendText(Output);
                    }
                }
            }

            Server.Disconnect(reason, canReconnect);
        }

        /// <summary>
        /// This method removes the ServerWindow from the TreeView
        /// </summary>

        public void Remove()
        {
            mainWindow.ChannelsTreeView.Items.Remove(ServerTreeViewItem);

            // Check if the current server eqals the server index.
            if (Server.Index == mainWindow.CurrentServerWindow)
            {
                // Clear the chatbox
                mainWindow.ChatBox.Document.Blocks.Clear();
            }

            // Remove the query list
            RemoveQueryList();
        }
    }
}
